/**
 * 
 */
package serialisierung;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import fpt.com.Product;

public class XMLStrategy implements
		fpt.com.SerializableStrategy {

	private FileOutputStream fo = null;
	private XMLEncoder encoder;

	private FileInputStream fi = null;
	private XMLDecoder decoder;

	@Override
	public Product readObject() throws IOException {
		
		if (fi == null) {
			fi = new FileInputStream("products.xml");
			decoder = new XMLDecoder(fi);
		}
		
		return (Product) decoder.readObject();

	}

	@Override
	public void writeObject(Product p) throws IOException {

		if (fo == null) {
			fo = new FileOutputStream("products.xml");
			encoder = new XMLEncoder(fo);
		}

		encoder.writeObject(p);
		encoder.flush();
	}

	@Override
	public void close() throws IOException {

		// Schließe Encoder
		if (encoder != null) {
			encoder.close();
		}

		// Schließe FileOutputStream
		if (fo != null) {
			fo.close();
			fo = null;
		}

		// Schließe Decoder
		if (decoder != null) {
			decoder.close();
		}

		// Schließe FileInputStream
		if (fi != null) {
			fi.close();
			fi = null;
		}
	}

}
